package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerRelationDepPerson.DepartmentPerson;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.Date;
import org.json.JSONException;

@SuppressWarnings("deprecation") public class CustomerRelationStaffDetailEditFragment
    extends BaseFragment implements OnClickListener {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.extra_value";
  protected static final String EXTRA_MEMBER = "com.isunland.managesystem.ui.extra_member";
  protected static final String TAG = CustomerRelationStaffDetailEditFragment.class.getName();
  private static final int REQUEST_BIRTH_DATE = 0;
  private static final int REQUEST_BEST_VISIT = 1;
  private static final int REQUEST_DEPTARTMENT = 4;
  private static final String BOY = "boy";
  private static final String GIRL = "girl";
  private static String mGender = BOY;
  private BaseVolleyActivity mActivity;
  private DepartmentPerson mStaffInfo;
  private EditText etStaffNoEdit;// 编号
  private EditText etStaffNameEdit;// 员工 姓名
  private RadioGroup tvDirectorSex;// 性别
  private RadioButton rbBoy;
  private RadioButton rbGirl;
  private EditText etStaffdialEdit;// 联系电话
  private EditText etStaffEmailEdit;// 邮箱
  private EditText etStaffDutyEdit;// 职务说明
  private TextView mTvBithDateEditDepartmentPerson;// 出生日期
  private EditText mTvBirthHomeEditDepartmentPerson;// 家乡地
  private EditText mTvHomeAddressEditDepartmentPerson;// 家庭住址
  private EditText mTvGraduateSchoolEditDepartmentPerson;// 毕业院校
  private EditText mTvPersonalEnjoyEditDepartmentPerson;// 个人喜好
  private TextView mTvBestVisitTimeEditDepartmentPerson;// 最佳拜访那个时间
  private EditText mTvPersonalRequireEditDepartmentPerson;// 个人需求
  private EditText mTvFamilyRelationEditDepartmentPerson;// 家庭成员及关系
  private EditText mTvOtherRemarkEditDepartmentPerson;// 其它说明与备注
  private SingleLineView slvWeChatNumber;
  private SingleLineView slvCustomer;
  private SingleLineView slvDepartment;

  public static Fragment newInstance(DepartmentPerson staffInfo) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, staffInfo);
    CustomerRelationStaffDetailEditFragment fragment =
        new CustomerRelationStaffDetailEditFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    setTitleCustom(MyStringUtil.connect(R.string.alter, R.string.customerContact1));
    mStaffInfo = (DepartmentPerson) getArguments().getSerializable(EXTRA_VALUE);
    mActivity = (BaseVolleyActivity) getActivity();
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_department_staff_detail_edit, container, false);
    etStaffNoEdit = (EditText) view.findViewById(R.id.et_staffNo_edit_departmentPerson);
    etStaffNameEdit = (EditText) view.findViewById(R.id.et__staffName_edit_departmentPerson);
    tvDirectorSex = (RadioGroup) view.findViewById(R.id.tv_directorSex_departmentEdit);
    rbBoy = (RadioButton) view.findViewById(R.id.rb_boy_epartmentPersonEdit);
    rbGirl = (RadioButton) view.findViewById(R.id.rb_girl_epartmentPersonEdit);
    etStaffdialEdit = (EditText) view.findViewById(R.id.et_staffdial_edit_departmentPerson);
    slvWeChatNumber = (SingleLineView) view.findViewById(R.id.slv_weChatNumber);
    slvCustomer = (SingleLineView) view.findViewById(R.id.slv_Customer);
    slvDepartment = (SingleLineView) view.findViewById(R.id.slv_department);
    etStaffEmailEdit = (EditText) view.findViewById(R.id.et_staffEmail_edit_departmentPerson);
    etStaffDutyEdit = (EditText) view.findViewById(R.id.et_staffDuty_edit_departmentPerson);

    mTvBithDateEditDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_bithDate_EditDepartmentPerson);
    mTvBirthHomeEditDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_birthHome_EditDepartmentPerson);
    mTvHomeAddressEditDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_homeAddress_EditDepartmentPerson);
    mTvGraduateSchoolEditDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_graduateSchool_EditDepartmentPerson);
    mTvPersonalEnjoyEditDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_personalEnjoy_EditDepartmentPerson);
    mTvBestVisitTimeEditDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_bestVisitTime_EditDepartmentPerson);
    mTvPersonalRequireEditDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_personalRequire_EditDepartmentPerson);
    mTvFamilyRelationEditDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_familyRelation_EditDepartmentPerson);
    mTvOtherRemarkEditDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_otherRemark_EditDepartmentPerson);

    mTvBithDateEditDepartmentPerson.setOnClickListener(this);
    mTvBestVisitTimeEditDepartmentPerson.setOnClickListener(this);
    initCustomerData();
    DynamicConfigLab config =
        DynamicConfigLab.newInstance(mActivity, getString(R.string.module_deptColumns));
    config.autoConfigTitle(view);
    config.autoConfigVisiblity(view);
    return view;
  }

  private void initCustomerData() {
    String staffNo = mStaffInfo.getStaffNo();
    String staffName = mStaffInfo.getStaffName();
    String staffGender = mStaffInfo.getStaffGender();
    String staffDial = mStaffInfo.getContactNum();
    String staffEmail = mStaffInfo.getContactMail();
    String staffDuty = mStaffInfo.getDutyDescript();
    String birthday = mStaffInfo.getBirthDate();
    String birthHome = mStaffInfo.getHomeArea();
    String homeAddress = mStaffInfo.getHomeAddress();
    String graduateSchool = mStaffInfo.getGraduateCollege();
    String personalEnjoy = mStaffInfo.getPersonalHobby();
    String bestVisitTime = mStaffInfo.getVisitTime();
    String personalRequire = mStaffInfo.getPersonalNeed();
    String familyRelation = mStaffInfo.getFamilyRelation();
    String otherRemark = mStaffInfo.getExplainRemark();

    if (!TextUtils.isEmpty(staffNo)) {
      etStaffNoEdit.setText(staffNo);
    }
    if (!TextUtils.isEmpty(staffName)) {
      etStaffNameEdit.setText(staffName);
    }
    if (!TextUtils.isEmpty(staffDial)) {
      etStaffdialEdit.setText(staffDial);
    }
    slvWeChatNumber.setTextContent(mStaffInfo == null ? "" : mStaffInfo.getWeChatCode());
    slvCustomer.setTextContent(mStaffInfo == null ? "" : mStaffInfo.getBlongCustomerName());
    slvCustomer.setInputEnabled(false);
    slvDepartment.setTextContent(mStaffInfo == null ? "" : mStaffInfo.getBlongOrgName());
    slvDepartment.setOnClickContentListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new CustomerRelationSuperDepartmentDialogFragment(), REQUEST_DEPTARTMENT);
      }
    });
    if (!TextUtils.isEmpty(staffEmail)) {
      etStaffEmailEdit.setText(staffEmail);
    }
    if (!TextUtils.isEmpty(staffDuty)) {
      etStaffDutyEdit.setText(staffDuty);
    }
    String boy = getString(R.string.boy_customerRel);
    String girl = getString(R.string.girl_customerRel);
    if (boy.equalsIgnoreCase(staffGender)) {
      rbBoy.setChecked(true);
    } else if (girl.equalsIgnoreCase(staffGender)) {
      rbGirl.setChecked(true);
    }

    tvDirectorSex.setOnCheckedChangeListener(new OnCheckedChangeListener() {

      @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
          case R.id.rb_boy_epartmentPersonEdit:
            // rbBoy.setChecked(true);
            mGender = BOY;
            break;
          case R.id.rb_girl_epartmentPersonEdit:
            // rbGirl.setChecked(true);
            mGender = GIRL;
            break;

          default:
            break;
        }
      }
    });
    if (!TextUtils.isEmpty(birthday)) {
      mTvBithDateEditDepartmentPerson.setText(birthday);
    }
    if (!TextUtils.isEmpty(birthHome)) {
      mTvBirthHomeEditDepartmentPerson.setText(birthHome);
    }
    if (!TextUtils.isEmpty(homeAddress)) {
      mTvHomeAddressEditDepartmentPerson.setText(homeAddress);
    }
    if (!TextUtils.isEmpty(graduateSchool)) {
      mTvGraduateSchoolEditDepartmentPerson.setText(graduateSchool);
    }
    if (!TextUtils.isEmpty(personalEnjoy)) {
      mTvPersonalEnjoyEditDepartmentPerson.setText(personalEnjoy);
    }
    if (!TextUtils.isEmpty(bestVisitTime)) {
      mTvBestVisitTimeEditDepartmentPerson.setText(bestVisitTime);
    }
    if (!TextUtils.isEmpty(personalRequire)) {
      mTvPersonalRequireEditDepartmentPerson.setText(personalRequire);
    }
    if (!TextUtils.isEmpty(familyRelation)) {
      mTvFamilyRelationEditDepartmentPerson.setText(familyRelation);
    }
    if (!TextUtils.isEmpty(otherRemark)) {
      mTvOtherRemarkEditDepartmentPerson.setText(otherRemark);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_confirm:
        isIfComplete();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void isIfComplete() {
    String email = etStaffEmailEdit.getText().toString().trim();
    if (TextUtils.isEmpty(email)) {
      volleyPostSave();
    } else {
      if (!MyUtils.isEmail(email)) {
        Toast.makeText(getActivity(), R.string.emailPatternWrong, Toast.LENGTH_SHORT).show();
        return;
      }
      volleyPostSave();
    }
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_STAFF_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    String id = mStaffInfo.getId();
    String staffNo = etStaffNoEdit.getText().toString();
    String staffName = etStaffNameEdit.getText().toString();
    String gender = "";
    if (mGender.equalsIgnoreCase(BOY)) {
      gender = getResources().getString(R.string.boy_customerRel);
    } else if (mGender.equalsIgnoreCase(GIRL)) {
      gender = getResources().getString(R.string.girl_customerRel);
    }
    String blongOrgCode = mStaffInfo.getBlongOrgCode();
    String blongCustomerCode = mStaffInfo.getBlongCustomerCode();
    String contactNum = etStaffdialEdit.getText().toString();
    String weChat = slvWeChatNumber.getTextContent();
    String contactMail = etStaffEmailEdit.getText().toString();
    String dutyDescript = etStaffDutyEdit.getText().toString();

    mStaffInfo.setContactMail(contactMail);
    mStaffInfo.setContactNum(contactNum);
    mStaffInfo.setStaffNo(staffNo);
    mStaffInfo.setStaffGender(gender);
    mStaffInfo.setStaffName(staffName);
    mStaffInfo.setDutyDescript(dutyDescript);
    mStaffInfo.setBirthDate(mTvBithDateEditDepartmentPerson.getText().toString());
    mStaffInfo.setHomeArea(mTvBirthHomeEditDepartmentPerson.getText().toString());
    mStaffInfo.setHomeAddress(mTvHomeAddressEditDepartmentPerson.getText().toString());
    mStaffInfo.setGraduateCollege(mTvGraduateSchoolEditDepartmentPerson.getText().toString());
    mStaffInfo.setPersonalHobby(mTvPersonalEnjoyEditDepartmentPerson.getText().toString());
    mStaffInfo.setVisitTime(mTvBestVisitTimeEditDepartmentPerson.getText().toString());
    mStaffInfo.setPersonalNeed(mTvPersonalRequireEditDepartmentPerson.getText().toString());
    mStaffInfo.setFamilyRelation(mTvFamilyRelationEditDepartmentPerson.getText().toString());
    mStaffInfo.setExplainRemark(mTvOtherRemarkEditDepartmentPerson.getText().toString());
    mStaffInfo.setWeChatCode(slvWeChatNumber.getTextContent());
    if (id != null) {
      params.put("id", id);
    } else {
      params.put("id", "");
    }
    params.put("staffNo", staffNo);
    params.put("staffName", staffName);
    params.put("staffGender", gender);

    params.put("contactNum", contactNum);
    params.put("weChatCode", weChat);
    params.put("contactMail", contactMail);
    params.put("dutyDescript", dutyDescript);
    if (!TextUtils.isEmpty(mTvBithDateEditDepartmentPerson.getText().toString())) {
      params.put("birthDate", mTvBithDateEditDepartmentPerson.getText().toString());
    } else {
      params.put("birthDate", "");
    }

    if (!TextUtils.isEmpty(mTvBirthHomeEditDepartmentPerson.getText().toString().trim())) {
      params.put("homeArea", mTvBirthHomeEditDepartmentPerson.getText().toString().trim());
    } else {
      params.put("homeArea", "");
    }

    if (!TextUtils.isEmpty(mTvHomeAddressEditDepartmentPerson.getText().toString().trim())) {
      params.put("homeAddress", mTvHomeAddressEditDepartmentPerson.getText().toString().trim());
    } else {
      params.put("homeAddress", "");
    }
    if (!TextUtils.isEmpty(mTvGraduateSchoolEditDepartmentPerson.getText().toString().trim())) {
      params.put("graduateCollege",
          mTvGraduateSchoolEditDepartmentPerson.getText().toString().trim());
    } else {
      params.put("graduateCollege", "");
    }
    if (!TextUtils.isEmpty(mTvPersonalEnjoyEditDepartmentPerson.getText().toString().trim())) {
      params.put("personalHobby", mTvPersonalEnjoyEditDepartmentPerson.getText().toString().trim());
    } else {
      params.put("personalHobby", "");
    }
    if (!TextUtils.isEmpty(mTvBestVisitTimeEditDepartmentPerson.getText().toString())) {
      params.put("visitTime", mTvBestVisitTimeEditDepartmentPerson.getText().toString());
    } else {
      params.put("visitTime", "");
    }
    if (!TextUtils.isEmpty(mTvPersonalRequireEditDepartmentPerson.getText().toString().trim())) {
      params.put("personalNeed",
          mTvPersonalRequireEditDepartmentPerson.getText().toString().trim());
    } else {
      params.put("personalNeed", "");
    }
    if (!TextUtils.isEmpty(mTvFamilyRelationEditDepartmentPerson.getText().toString().trim())) {
      params.put("familyRelation",
          mTvFamilyRelationEditDepartmentPerson.getText().toString().trim());
    } else {
      params.put("familyRelation", "");
    }
    if (!TextUtils.isEmpty(mTvOtherRemarkEditDepartmentPerson.getText().toString().trim())) {
      params.put("explainRemark", mTvOtherRemarkEditDepartmentPerson.getText().toString().trim());
    } else {
      params.put("explainRemark", "");
    }
    params.put("blongOrgCode", blongOrgCode);
    params.put("blongCustomerCode", blongCustomerCode);
    params.put("blongCustomerName", slvCustomer.getTextContent());
    params.put("blongOrgName", slvDepartment.getTextContent());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            // set性别。
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            Intent i = new Intent();
            i.putExtra(EXTRA_MEMBER, mStaffInfo);
            getActivity().setResult(Activity.RESULT_OK, i);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.tv_bithDate_EditDepartmentPerson:
        showDialog(REQUEST_BIRTH_DATE, new Date());
        break;
      case R.id.tv_bestVisitTime_EditDepartmentPerson:
        showDialog(REQUEST_BEST_VISIT, new Date());
        break;

      default:
        break;
    }
  }

  /**
   * 显示时间对话框
   *
   * @param requestCode 请求码
   * @param date 对话框初始显示时间
   */
  public void showDialog(int requestCode, Date date) {

    DialogFragment dialog = null;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (requestCode) {
      case REQUEST_BIRTH_DATE:
        dialog = new BaseYMDTimeDialogFragment();
        break;
      case REQUEST_BEST_VISIT:
        dialog = WorkProgressTimeDialogFragment.newInstance(date, R.string.chooseBestVisit);
        break;
      default:
        break;
    }
    if (dialog == null) return;
    dialog.setTargetFragment(CustomerRelationStaffDetailEditFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_BIRTH_DATE && data != null) {
      Date birthDate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String mBirthDate = MyDateUtil.dateToString(birthDate, MyDateUtil.TYPE_DATE);
      mTvBithDateEditDepartmentPerson.setText(mBirthDate);
      return;
    }
    if (requestCode == REQUEST_BEST_VISIT && data != null) {
      Date visitTime = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      String mVisitTime = MyDateUtil.dateToString(visitTime, MyDateUtil.TYPE_ALL);
      mTvBestVisitTimeEditDepartmentPerson.setText(mVisitTime);
    }
    if (requestCode == REQUEST_DEPTARTMENT && data != null) {

      CustomerDialog department = (CustomerDialog) data.getSerializableExtra(
          CustomerRelationSuperDepartmentDialogFragment.EXTRA_VALUE);
      mStaffInfo.setBlongOrgCode(department.getId());
      mStaffInfo.setBlongOrgName(department.getName());
      slvDepartment.setTextContent(department.getName());
    }
  }
}
